package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.socket.WebSocketServer;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //校验信息是否正确
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook==null){
            //没有填写地址信息
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //信息合法  获取购物车信息
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.findCartByID(userId);
        if(shoppingCarts==null|| shoppingCarts.isEmpty()){
            //购物车为空  不能下单
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //购物车不为空且信息正确  可以下单
        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());//收货人
        order.setNumber(String.valueOf(System.currentTimeMillis()));//订单编号
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);//订单状态
        order.setPayStatus(Orders.UN_PAID);//支付状态
        order.setOrderTime(LocalDateTime.now());//下单时间
        //向数据库插入一条订单数据
        orderMapper.saveOrder(order);
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //获取订单id
        Long id = order.getId();
        shoppingCarts.forEach(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(id);
            orderDetailList.add(orderDetail);
        });
        //向数据库插入多条订单详细信息
        orderMapper.saveOrderDetails(orderDetailList);
        //构造一个OrderVO
        OrderSubmitVO orderVO = OrderSubmitVO.builder()
                .id(id)
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();
        //清空购物车
        shoppingCartMapper.clean(userId);
        return orderVO;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        //TODO 此处需要商家资格才能调用 模拟支付成功
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
        //模拟支付成功返回数据
        JSONObject jo = new JSONObject();

        jo.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
        jo.put("nonceStr", RandomStringUtils.randomNumeric(32));
        jo.put("package", "prepay_id=" + UUID.randomUUID());
        jo.put("signType", "RSA");
        jo.put("paySign",  "RSA");
        OrderPaymentVO vo = jo.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jo.getString("package"));
        //模拟支付成功 修改订单状态
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        Map map = new HashMap();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号"+outTradeNo);
        webSocketServer.sendToAllServer(JSONObject.toJSONString(map));
    }

    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //设置用户id
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> pages = orderMapper.historyOrders(ordersPageQueryDTO);
        long total = pages.getTotal();//查询到的总条数
        List<OrderVO> list = new ArrayList<>();
        pages.forEach(page->{
            List<OrderDetail> orderDetails = orderMapper.getOrderDetails(page.getId());
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(page,orderVO);
            orderVO.setOrderDetailList(orderDetails);
            list.add(orderVO);
        });

        PageResult pageResult = new PageResult();
        pageResult.setTotal(total);
        pageResult.setRecords(list);
        return pageResult;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderDetail(Long id) {
        Orders order=orderMapper.getOrder(id);
        List<OrderDetail> orderDetails = orderMapper.getOrderDetails(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order,orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) {
        //根据id号查询订单
        Orders odd_order = orderMapper.getOrder(id);
        if(odd_order==null){
            //订单不存在
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //查看订单的状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
       if( odd_order.getStatus()>2){
           throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
       }
       //当前订单状态正常 调用接口退款
        //TODO 调用微信接口退款
        log.info("模拟微信退款");
        Orders orders = new Orders();
        BeanUtils.copyProperties(odd_order,orders);
        orders.setStatus(Orders.CANCELLED);//修改订单状态
        orders.setCancelReason("多拍，错拍，不想要");//用户取消原因
        orders.setCancelTime(LocalDateTime.now());//取消时间
        orders.setPayStatus(Orders.REFUND);//支付状态修改为退款
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //通过查询订单详情获取商品
        List<OrderDetail> orderDetails = orderMapper.getOrderDetails(id);
        List<ShoppingCart> list = new ArrayList<>();
        orderDetails.forEach(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart,"id");
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            list.add(shoppingCart);
        });
        //向购物车添加数据
        shoppingCartMapper.addMore(list);
    }

    /**
     * 管理端订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //获取到订单信息
        Page<Orders> page=orderMapper.conditionSearch(ordersPageQueryDTO);
        //获取订单的详细信息
        long total = page.getTotal();
        List<OrderVO> orderList = getOrderList(page);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(total);
        pageResult.setRecords(orderList);
        return pageResult;
    }

    /**
     * 获取订单菜品的详细信息
     */
    public  List<OrderVO> getOrderList(List<Orders> orders){
        List<OrderVO> list = new ArrayList();
        orders.forEach(order -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order,orderVO);
            List<OrderDetail> orderDetails = orderMapper.getOrderDetails(order.getId());
//            orderVO.setOrderDetailList(orderDetails);
//            orderVO.setOrderDishes("椒麻鱼");
            List<String> orderDetailsList = orderDetails.stream().map(x -> {
                String orderDish=x.getName()+"*"+x.getNumber();
                return orderDish;
            }).collect(Collectors.toList());
            //把所有的菜品信息拼接到一起
            String join = String.join(";", orderDetailsList);
            orderVO.setOrderDishes(join);
            list.add(orderVO);
        });
        return list;
    }
    /**
     * 统计各个订单的数量
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        Integer toBeConfirmed = orderMapper.statistics(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.statistics(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.statistics(Orders.DELIVERY_IN_PROGRESS);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 获取制定订单的详细信息
     * @param id
     * @return
     */
    @Override
    public OrderVO getDetails(Long id) {
        Orders order = orderMapper.getOrder(id);
        List<OrderDetail> orderDetails = orderMapper.getOrderDetails(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order,orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }
    /**
     * 商家接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .id(ordersConfirmDTO.getId())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 商家拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //1.获取当前订单状态 状态为待接单才能拒绝
        Orders orderDB = orderMapper.getOrder(ordersRejectionDTO.getId());
        if(orderDB.getStatus()!=Orders.TO_BE_CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //2.用户已经下单 需要进行退款
        log.info("用户退款完成！");//todo 调用微信接口退款
        //3.修改订单状态接拒单原因
        Orders order = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(order);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //1.检查当前订单是否存在 且订单状态为已接单
        Orders order = orderMapper.getOrder(id);
        if(order==null || !order.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //2.修改订单状态为派送中
        Orders o = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(o);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        //1.查看订单是否存在且状态为派送中
        Orders order = orderMapper.getOrder(id);
        if(order==null || !order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //2.修改订单状态为已完成
        Orders o = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(o);
    }
    /**
     * 商家取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
       //1.查看订单支付状态
        Orders order = orderMapper.getOrder(ordersCancelDTO.getId());
        if (order.getPayStatus().equals(Orders.PAID)){
            //已支付，进行退款
            //todo 调用微信接口退款
            log.info("退款成功！");
        }
        //修改订单状态
        Orders o = Orders.builder()
                .id(order.getId())
                .cancelTime(LocalDateTime.now())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .payStatus(Orders.REFUND)
                .status(Orders.CANCELLED)
                .build();
        orderMapper.update(o);
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号"+orderMapper.getOrder(id).getNumber());
        String msg = JSON.toJSONString(map);
        webSocketServer.sendToAllServer(msg);
    }
}

